package com.wgz.flag.service.impl;

import com.wgz.flag.domain.dto.GroupChatDTO;
import com.wgz.flag.domain.vo.GroupChatVO;
import com.wgz.flag.entity.GroupChat;
import com.wgz.flag.entity.GroupMember;
import com.wgz.flag.entity.User;
import com.wgz.flag.exception.BaseException;
import com.wgz.flag.mapper.GroupChatMapper;
import com.wgz.flag.mapper.GroupMemberMapper;
import com.wgz.flag.mapper.UserMapper;
import com.wgz.flag.service.GroupChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class GroupChatServiceImpl implements GroupChatService {

    private final GroupChatMapper groupChatMapper;
    private final GroupMemberMapper groupMemberMapper;
    private final UserMapper userMapper;

    @Override
    @Transactional
    public GroupChatVO createGroup(Long userId, GroupChatDTO groupChatDTO) {
        // 创建群聊
        GroupChat groupChat = new GroupChat();
        BeanUtils.copyProperties(groupChatDTO, groupChat);
        groupChat.setOwnerId(userId);
        groupChat.setStatus(1);
        groupChat.setCreateTime(LocalDateTime.now());
        groupChat.setUpdateTime(LocalDateTime.now());
        groupChatMapper.insert(groupChat);

        // 添加群主为群成员
        GroupMember owner = new GroupMember();
        owner.setGroupId(groupChat.getId());
        owner.setUserId(userId);
        owner.setNickname(userMapper.selectById(userId).getNickname());
        owner.setRole(2); // 群主角色
        owner.setStatus(1);
        owner.setJoinTime(LocalDateTime.now());
        groupMemberMapper.insert(owner);

        // 将拉取的成员加入群聊
        if (groupChatDTO.getMemberIds() != null && !groupChatDTO.getMemberIds().isEmpty()) {
            List<GroupMember> members = groupChatDTO.getMemberIds().stream()
                    .map(targetId -> {
                        User user = userMapper.selectById(targetId);
                        if (user == null) {
                            throw new BaseException("用户不存在");
                        }
                        GroupMember groupMember = new GroupMember();
                        groupMember.setGroupId(groupChat.getId());
                        groupMember.setUserId(user.getId());
                        groupMember.setNickname(user.getNickname());
                        groupMember.setRole(0);
                        groupMember.setStatus(1);
                        groupMember.setJoinTime(LocalDateTime.now());
                        groupMember.setUpdateTime(LocalDateTime.now());
                        return groupMember;
                    })
                    .collect(Collectors.toList());
            log.info("members: {}", members);
            groupMemberMapper.insertBatch(members);
        }

        return convertToVO(groupChat);
    }

    /**
     * 获取群聊列表
     */
    @Override
    public List<GroupChatVO> getGroupList(Long userId) {
        List<GroupChat> groups = groupChatMapper.selectByUserId(userId);
        return groups.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public void updateGroup(Long groupId, GroupChatDTO groupChatDTO) {
        GroupChat groupChat = groupChatMapper.selectById(groupId);
        if (groupChat == null || groupChat.getStatus() == 0) {
            throw new BaseException("群聊不存在");
        }
        
        BeanUtils.copyProperties(groupChatDTO, groupChat);
        groupChatMapper.update(groupChat);
    }

    @Override
    @Transactional
    public void dismissGroup(Long groupId, Long userId) {
        GroupChat groupChat = groupChatMapper.selectById(groupId);
        if (groupChat == null || groupChat.getStatus() == 0) {
            throw new BaseException("群聊不存在");
        }
        
        if (!groupChat.getOwnerId().equals(userId)) {
            throw new BaseException("只有群主能解散群聊");
        }

        // 更新群聊状态
        groupChatMapper.updateStatus(groupId, 0);
        
        // 更新所有成员状态
        groupMemberMapper.updateStatus(groupId, null, 0);
    }

    private GroupChatVO convertToVO(GroupChat groupChat) {
        if (groupChat == null) {
            return null;
        }
        GroupChatVO vo = new GroupChatVO();
        BeanUtils.copyProperties(groupChat, vo);
        // TODO: 可以添加其他需要的信息，如成员数量等
        return vo;
    }
}